package com.xy.cloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xy.cloud.domain.R;
import com.xy.cloud.domain.dto.UserAddMoneyDTO;
import com.xy.cloud.domain.entities.Order;
import com.xy.cloud.domain.entities.RocketmqTransactionLog;
import com.xy.cloud.feign.BackStageService;
import com.xy.cloud.mapper.OrderMapper;
import com.xy.cloud.service.OrderService;
import com.xy.cloud.service.RocketmqTransactionLogService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;
import java.util.UUID;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RocketmqTransactionLogService rocketmqTransactionLogService;

    @Autowired
    private BackStageService backStageService;

    @Override
    public void delete(String orderNo) {
        Order order = this.lambdaQuery().eq(Order::getOrderNo, orderNo).one();
        //如果订单存在且状态为有效，进行业务处理
        if (Objects.equals(order.getStatus(), "1")) {
            String transactionId = UUID.randomUUID().toString();
            //如果可以删除订单则发送消息给rocketmq，让用户中心消费消息

            //目的地(主题)， 发送给消费者的消息体,参数
            rocketMQTemplate.sendMessageInTransaction("add-amount",
                    MessageBuilder.withPayload(
                                    UserAddMoneyDTO.builder()
                                            .userCode(order.getAccountCode())
                                            .amount(order.getAmount())
                                            .build()
                            )
                            .setHeader(RocketMQHeaders.TRANSACTION_ID, transactionId)
                            .setHeader("order_id", order.getId())
                            .build()
                    , order
            );

        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeStatuswithRocketMqLog(String orderId, String transactionId) {
        this.lambdaUpdate().set(Order::getStatus, "0").eq(Order::getId, orderId).update();

        RocketmqTransactionLog rocketMqLog = new RocketmqTransactionLog();
        rocketMqLog.setTransactionId(transactionId);
        rocketMqLog.setLog("状态修改成功");
        rocketmqTransactionLogService.save(rocketMqLog);
    }



    @GlobalTransactional(name="orderSave")
    @Override
    public void save() {
        Order order = new Order();
        order.setId("1");
        order.setOrderNo("666");
        this.updateById(order);
        log.info("order 添加完毕，即将发送OpenFeign==========");
        String xid = RootContext.getXID();
        log.info("XID: {}",xid);
        R<?> save = backStageService.save();
        log.info("OpenFeign返回结果：{}", JSON.toJSONString(save));
    }
}
